package game.resource.loader;

import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DataBufferByte;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import common.Log;

import engine.Constants;
import engine.Globals;
import engine.filesystem.FileScanner;
import engine.video.blit.PixelBuffer;
import engine.video.palette.Palette;

public class PixelBufferLoader {
	public static PixelBuffer load(InputStream stream) {
		BufferedImage img = null;
		try {
			img = ImageIO.read(stream);
		} catch (IOException e) {
			Log.error("Error loading pixel buffer from input stream.");
			e.printStackTrace();
		}
		if(img == null) {
			return null;
		}
		byte[] pixels;
		ColorModel model = img.getColorModel();
		if(model.getPixelSize() == Constants.SCREEN_BPP) {
			pixels = copyImage8_BPP(img);
		} else {
			pixels = convertImage(img);
		}
		return new PixelBuffer(img.getWidth(), img.getHeight(), pixels);
	}
	
	public static PixelBuffer load(String fileName, FileScanner scanner) {
		InputStream stream = scanner.openFile(fileName);
		PixelBuffer output = PixelBufferLoader.load(stream);
		try {
			stream.close();
		} catch (IOException e) {
			Log.error("SpriteBuilder.loadPixelBuffer() : Unable to close file stream.");
		}
		return output;
	}
	public static byte[] copyImage8_BPP(BufferedImage image) {
		DataBufferByte dBuffer = (DataBufferByte)image.getData().getDataBuffer();
		byte[] pixels = dBuffer.getData();
		return pixels;
	}
	public static byte[] convertImage(BufferedImage image) {
		int w = image.getWidth();
		int h = image.getHeight();
		byte[] pixels = new byte[w * h];
		Palette pal = Globals.GamePalette;
		int c , r, g, b;
		int index = 0;
		for(int y = 0; y < h; y++) {
			for(int x = 0; x < w; x++) {
				c = image.getRGB(x, y);
				r = (c >> 16) & 0xFF;
				g = (c >> 8) & 0xFF;
				b = c & 0xFF;
				pixels[index++] = (byte)pal.getIndexofColor(r, g, b);
			}
		}
		return pixels;
	}

}
